/**
 * 权限管理
 * 
 * @returns {undefined}
 */
$(function () {

    var permissions = $("#permissions"),
        employees = $("#employees"),
        waiting = $("#waiting"),
        loading = $("#loading"),
        roleContainer = $("#roleContainer"),
        name = $("#roleName"),
        saveRoleMembers = $("#saveRoleMembers"),
        // 缓存
        currentRoleId = null,
        roleCache = {}, //角色列表
        group = {}, //权限列表
        ajax_response = 0;//ajax请求返回标志

    /**
     * 确认页面ajax请求是否全部加载完毕
     * 
     * TODO: use $.when().done();
     * 
     */
    var ajaxSuccess = function () {
        ajax_response += 1;
        if (ajax_response === 3) { // all loaded
            $("li.roleItem").first().trigger("click");
        }
    };

    /**
     * 加载员工列表
     */
    var empMap = [], otherMap = [];

    var loadEmployees = function (id) {
        $.get("permission/listEmployeeByRole/" + id, function (data) {
            if (data) {
                var emps = data.employees, others = data.others;
                for (var i = 0; i < emps.length; i++) {
                    empMap.push(emps[i].id);
                }
                for (var i = 0; i < others.length; i++) {
                    otherMap.push(others[i].id);
                }

                var rendered = sys.render("#employeeListTemplate", {data: emps});
                employees.html($(rendered));
                rendered = sys.render("#employeeWaitingTemplate", {data: others});
                waiting.html($(rendered));
            } else {
                $("#employees .load-info").html("尚未添加员工");
            }
            ajaxSuccess();
        }).fail(function () {
            alert("加载员工列表失败：服务器错误");
        });
    };

    /**
     * 加载权限列表
     */
    var loadPermissions = function () {
        var leftCol = $(".leftCol"),
            rightCol = $(".rightCol");

        $.get("permission/listPermissions", function (data) {
            if (data && data.length > 0) {
                var groupSize = 0;
                for (var i = 0; i < data.length; i++) {
                    var permission = data[i];
                    if (permission.group in group) {
                        group[permission.group].push(permission);
                    } else {
                        group[permission.group] = [permission];
                        groupSize++;
                    }
                }
                var map = {};
                // 渲染权限标志
//                map.mode = function () {
//                    return this.name.indexOf("ADMIN") !== -1
//                        ? '<span class="label label-xs alert-success pastel ml10 fw600">读写</span>'
//                        : '<span class="label label-xs alert-warning pastel ml10 fw600">只读</span>';
//                };
                //permissions.html("");
                $(".p-load-info").hide();
                var mid = groupSize / 2, count = 0;
                for (var key in group) {
                    var ps = group[key], groupLabel = $('<label class="control-label mb15"></label>').html(key);
                    map.result = ps;
                    var rendered = sys.render("#permissionTemplate", map);
                    if (count < mid) {
                        leftCol.append(groupLabel).append($('<div class="form-group mn mb10 pl20"></div>').html(rendered));
                    } else {
                        rightCol.append(groupLabel).append($('<div class="form-group mn mb10 pl20"></div>').html(rendered));
                    }
                    count++;
                }
            } else {
                $("#permissions .load-info").text("尚未添加权限");
            }
            ajaxSuccess();
        }).fail(function () {
            alert("加载权限列表失败：服务器错误");
        });
    };

    /**
     * 加载角色列表
     */
    var loadRoles = function () {
        $.get("permission/listRoles", function (roles) {
            if (roles && roles.recordsTotal > 0) {
                // 渲染角色
                var rendered = sys.render("#roleListTemplate", {"roles": roles.data});
                loading.remove();
                roleContainer.html(rendered);

                // 缓存角色列表
                $.map(roles.data, function (role) {
                    roleCache[role.id] = role;
                });
            } else {
                loading.html('<span class="glyphicons glyphicons-user mr10"></span>尚未添加角色');
            }
            ajaxSuccess();
        }).fail(function () {
            alert("加载角色列表失败：服务器错误");
        });
    };

    /**
     * 保存角色
     * 
     * @param {type} id
     * @returns {undefined}
     */
    var saveRole = function (role) {
        $.post("permission/saveRole", role, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
        }).fail(function () {
            alert("服务器错误");
        });
    };

    /**
     * 清除权限和员工选择框
     */
    var clearPermissionAndEmployeeCheckbox = function () {
        $(".permission_checkbox").prop("checked", false);
        $(".member_checkbox").prop("checked", false);
    };

    /**
     * 绑定页面响应事件
     */
    var initEvents = function () {
        // 删除员工
        employees.on("click", ".remove-emp-link", function (e) {
            $(this).html('<i class="fa fa-plus text-muted"></i> 添加').closest(".empWrapper").appendTo(waiting);
            saveRoleMembers.show();
        });
        // 添加员工
        waiting.on("click", ".remove-emp-link", function (e) {
            $(this).html('<i class="fa fa-trash text-muted"></i> 移除').closest(".empWrapper").appendTo(employees);
            saveRoleMembers.show();
        });
        // 角色详情
        roleContainer.on("click", "li.roleItem", function (e) {
            var id = $(this).data("id"), role = roleCache[id];
            $("li.roleItem").removeClass("active");
            $(this).addClass("active");
            clearPermissionAndEmployeeCheckbox();
            if (role) {
                name.val(role.name);
                //description.val(role.description);
                currentRoleId = id;

                loadEmployees(id);

                // 读取权限列表
                for (var i = 0; i < role.permissions.length; i++) {
                    var permission = role.permissions[i];
                    $(".permission_checkbox[value=" + permission.name + "]").prop("checked", true);
                }
                // 读取员工列表
                for (var i = 0; i < role.members.length; i++) {
                    var employee = role.members[i];
                    $(".member_checkbox[value=" + employee.id + "]").prop("checked", true);
                }
            }
        });
        // 删除角色按钮
        roleContainer.on("click", "li .delete-role-link", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var url = "permission/deleteRole/" + $(this).data("id");
            if (confirm("确定删除角色")) {
                $.get(url, function (res) {
                    if (res) {
                        alert("角色已删除");
                        location.reload();
                    } else {
                        alert("角色删除失败");
                    }
                }).fail(function () {
                    alert("服务器错误");
                });
            }
        });
        // 保存角色按钮
        $("#saveRoleBtn").on("click", function () {
            if (name.val() === '') {
                alert("请输入角色名称");
                name.focus();
                return;
            }
            var role = {
                id: currentRoleId,
                name: name.val(),
                permissions: '',
                members: ''//members.join(","),
            };
            saveRole(role);
        });
        // 保存角色权限
        $("#saveRolePermission").on("click", function () {
            var permissions = [];
            $.map($(".permission_checkbox:checked"), function (box) {
                permissions.push($(box).val());
            });
//        $.map($(".member_checkbox:checked"), function (box) {
//            members.push($(box).val());
//        });
            var role = {
                id: currentRoleId,
                name: name.val(),
                permissions: permissions.join(","),
                members: ''//members.join(","),
            };
            saveRole(role);
        });

        var roleList = $("#roleList"),
            addRoleBox = $("#addRoleBox");


        // 添加角色按钮
        $("#add_role").on("click", function () {
            clearPermissionAndEmployeeCheckbox();
            currentRoleId = null;
            name.val("");
            roleList.hide();
            addRoleBox.show();
        });

        // 取消添加角色
        $("#cancelAdd").on("click", function () {
            addRoleBox.hide();
            roleList.show();
        });

        // 取消添加角色
        saveRoleMembers.on("click", function () {
            var add = [], remove = [], btn = $(this);
            sys.btnSpin(btn);
            $.each($("#employees .remove-emp-link"), function () {
                var id = $(this).data("id");
                if (empMap.indexOf(id) === -1) {
                    add.push(id);
                }
            });
            $.each($("#waiting .remove-emp-link"), function () {
                var id = $(this).data("id");
                if (otherMap.indexOf(id) === -1) {
                    remove.push(id);
                }
            });

            $.post("permission/saveRoleForEmployees", {
                roleId: currentRoleId,
                addIdString: add.join(","),
                cancelIdString: remove.join(",")

            }, function (res) {
                sys.alert(res.message);
                sys.btnStop(btn);
            }).fail(function () {
                alert("网络通信错误");
                sys.btnStop(btn);
            });
        });
    };

    var initPage = function () {
        loadRoles();
        loadPermissions();
        initEvents();
    };

    // 初始化页面
    initPage();
});